package user.view;

import static org.math.array.DoubleArray.increment;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;

import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import javax.swing.border.Border;
import javax.swing.text.JTextComponent;

import model.doe.FresnelCrossed;
import model.util.FourerExecutor;
import model.util.FourerExecutor.DoeType;

import system.activity.MainListener;
import system.elements.ControlTextField;
import system.util.PlotBuilder;

public class FresnelCrossedImpl extends Controls
{

    private javax.swing.JCheckBox phase;
    private javax.swing.JCheckBox fourer;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel descrStepLabel;
    private ControlTextField descrStepText;
    private javax.swing.JLabel heightFocalLengthLabel;
    private ControlTextField heightFocalLengthText;
    private javax.swing.JLabel heightLabel;
    private ControlTextField heightText;
    private javax.swing.JButton okButton;
    private javax.swing.JCheckBox signPhase;
    private javax.swing.JLabel widthFocalLengthLabel;
    private ControlTextField widthFocalLengthText;
    private javax.swing.JLabel widthLabel;
    private ControlTextField widthText;
    private javax.swing.JLabel wlLabel;
    private ControlTextField wlText;
 

	public FresnelCrossedImpl(final MainListener listener)
	{
		this.listener = listener;
		this.setLayout(new java.awt.BorderLayout());

		init();
	}
	public FresnelCrossedImpl(final MainListener listener, ArrayList<String> params)
	{
		this.listener = listener;
		this.setLayout(new java.awt.BorderLayout());
		initFromHistory(params);
	}
	
	@Override
	protected LinkedList<JTextComponent> elementsQueue()
	{
		LinkedList<JTextComponent> result = new LinkedList<JTextComponent>();
		result.add(heightText);
		result.add(widthText);
		result.add(heightFocalLengthText);
		result.add(widthFocalLengthText);
		result.add(wlText);
		result.add(descrStepText);
		return result;
	}
	
	@Override
	protected void init()
	{
        heightLabel = new javax.swing.JLabel();
        heightText = new ControlTextField();
        widthText = new ControlTextField();
        widthLabel = new javax.swing.JLabel();
        heightFocalLengthText = new ControlTextField();
        heightFocalLengthLabel = new javax.swing.JLabel();
        widthFocalLengthText = new ControlTextField();
        widthFocalLengthLabel = new javax.swing.JLabel();
        wlText = new ControlTextField();
        wlLabel = new javax.swing.JLabel();
        
        phase = new javax.swing.JCheckBox();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        signPhase = new javax.swing.JCheckBox();
        descrStepLabel = new javax.swing.JLabel();
        descrStepText = new ControlTextField();
        fourer = new javax.swing.JCheckBox();
        
        setName("Form"); // NOI18N

        heightLabel.setText("Высота");
        heightText.setText("1");
        widthText.setText("1");
        widthLabel.setText("Ширина");
        heightFocalLengthText.setText("100");
        heightFocalLengthLabel.setText("Фокус вертикальной линзы");
        widthFocalLengthText.setText("200");
        widthFocalLengthLabel.setText("Фокус горизонтальной линзы");
        wlText.setText("0.6");
        wlLabel.setText("Длина волны(микрон)");
        okButton.setText("Рассчитать");
        cancelButton.setText("Закрыть");
        descrStepLabel.setText("Шаг дискретизации"); // NOI18N
        descrStepText.setText("0.01");
        
        phase = new javax.swing.JCheckBox();
		signPhase = new javax.swing.JCheckBox();
		fourer = new javax.swing.JCheckBox();
		phase.setText("Расчет фазы");
		signPhase.setText("Расчет знака фазы");
		fourer.setText("Выполнить преобразование Фурье");

		fourer.setEnabled(false);
		phase.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				checkFourerAvailable();
			}

		});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(signPhase)
                    .addComponent(phase)
                    .addComponent(fourer)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(okButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(descrStepLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(wlLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(heightLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)
                            .addComponent(widthLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(heightFocalLengthLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(widthFocalLengthLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(wlText, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(widthFocalLengthText, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(heightFocalLengthText, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(widthText, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(heightText, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(descrStepText, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(heightLabel)
                    .addComponent(heightText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(widthLabel)
                    .addComponent(widthText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(heightFocalLengthLabel)
                    .addComponent(heightFocalLengthText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(widthFocalLengthLabel)
                    .addComponent(widthFocalLengthText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wlLabel)
                    .addComponent(wlText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(descrStepLabel)
                    .addComponent(descrStepText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(16, 16, 16)
                .addComponent(phase)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(signPhase)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fourer)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 90, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );
		okButton.addMouseListener(new java.awt.event.MouseAdapter()
		{
			public void mouseClicked(java.awt.event.MouseEvent evt)
			{
				try {
					okButton.setEnabled(false);
					final FresnelCrossed fresnel = new FresnelCrossed(Double.parseDouble(heightText.getText()), Double.parseDouble(widthText
							.getText()), Double.parseDouble(heightFocalLengthText.getText()), Double.parseDouble(widthFocalLengthText.getText()), Double.parseDouble(wlText.getText()),Double.parseDouble(descrStepText.getText()));
					listener.clearImagePanel();
					listener.setLoadStatus();
					java.awt.event.ActionListener actionListener = new java.awt.event.ActionListener()
					{
						public void actionPerformed(java.awt.event.ActionEvent actionEvent)
						{
							try {
								if (phase.isSelected()) {
									listener.addImagePanel(fresnel.getPhaseTo2PiMImage(), "Распределение фазы линзы");
								}
								if (signPhase.isSelected()) {
									listener.addImagePanel(fresnel.getSignPhaseImage(), "Распределение знака фазы");
								}
								if (phase.isSelected() && fourer.isSelected()) {
									FourerExecutor fourer = new FourerExecutor();
									ArrayList<BufferedImage> fourerImages = fourer.fft(fresnel, DoeType.PHASE);
									listener.addImagePanel(fourerImages.get(0),"Распредление амплитуды после преобразования Фурье");
									
									double[][] z = fourer.getResultAmpl();
									double[] x = increment(0d, 1d, z[0].length);
									double[] y = increment(0d, 1d, z.length);
									String plotDescription = "Распределение амплитуды после преобразования Фурье - график";
									listener.addFastPlotPanel(PlotBuilder.buildFast3DPlot(x, y, z, plotDescription), "Распределение амплитуды после преобразования Фурье - график");
									
									
									listener.addImagePanel(fourerImages.get(1),"Распредление фазы после преобразования Фурье");
									onResize();
									listener.needRepaint();
								}
								onResize();
								listener.needRepaint();
								listener.removeLoadStatus();
								okButton.setEnabled(true);
							} catch (OutOfMemoryError ex) {
								listener.removeLoadStatus();
								okButton.setEnabled(true);
								listener.showErrorMessage("Перепелнение памяти");
							}
							catch(IllegalArgumentException ex)
							{
								listener.removeLoadStatus();
								okButton.setEnabled(true);
								listener.showErrorMessage(ex.getMessage());
							}
						}
					};
					Timer timer = new Timer(500, actionListener);
					timer.setRepeats(false);
					timer.start();
				} catch (NumberFormatException ex) {
					listener.showErrorMessage("Ошибка формата входных данных");
					listener.removeLoadStatus();
					okButton.setEnabled(true);
				}
			}
		});
		cancelButton.addMouseListener(new java.awt.event.MouseAdapter()
		{
			public void mouseClicked(java.awt.event.MouseEvent evt)
			{
				listener.removeLeftPanel();
				onResize();
				listener.needRepaint();
			}
		});
		Border border = BorderFactory.createEtchedBorder(Color.white, new Color(178, 178, 178));
		this.setBorder(border);
		listener.addPanel(this);
		this.show();
	}

	void onResize()
	{
		this.show();
	}

	@Override
	public void setListener(MainListener listener)
	{
		this.listener = listener;
	}

	@Override
	public Collection<String> getControlsValues()
	{
		Date date = new Date();
		Collection<String> result = new ArrayList<String>();
		result.add("                                                                                 " + date.getHours() + ":" + date.getMinutes() + ":"
				+ date.getSeconds() + "   " + date.getDate() + "." + (date.getMonth() + 1) + "." + (date.getYear() + 1900));
		result.add("Линза Френеля скрещенная");
		result.add("Введенные параметры:");
		result.add(heightLabel.getText() + " = " + heightText.getText());
		result.add(widthLabel.getText() + " = " + widthText.getText());
		result.add(heightFocalLengthLabel.getText() + " = " + heightFocalLengthText.getText());
		result.add(widthFocalLengthLabel.getText() + " = " + widthFocalLengthText.getText());
		result.add(wlLabel.getText() + " = " + wlText.getText());
		result.add(descrStepLabel.getText() + " = " + descrStepText.getText());
		result.add("");
		return result;
	}
	@Override
	String getClassName()
	{
		return this.getClass().getCanonicalName();
	}
	private void checkFourerAvailable() {
		fourer.setEnabled(phase.isSelected());
		if(fourer.isEnabled() == false)
		{
			fourer.setSelected(false);
		}
	}
}
